var express = require('express');
var router = express.Router();
var _ = require('lodash');

const log = require('../../../core/logger').getLogger("system");
const helper = require('../../util/helper');
const roleService = require('../../services/admin/roleService');
const menuService = require('../../services/admin/menuService');

var formatMenus = function (menu_roles) {
    var menus = [];
    if (menu_roles.length) {
        for (var i = 0; i < menu_roles.length; i++) {
            var menuRoleObj = menu_roles[i];
            var parent_id = menuRoleObj['parent_id'];
            if (parent_id == 0) {
                var menuObj = {};
                menuObj['parent_id'] = parent_id;
                menuObj['menu_id'] = menuRoleObj['menu_id'];
                menuObj['menu_name'] = menuRoleObj['menu_name'];
                menuObj['menu_url'] = menuRoleObj['menu_url'];
                menuObj['menu_icon'] = menuRoleObj['menu_icon'];
                menuObj['menu_child'] = [];
                menus.push(menuObj);
            } else {
                for (var j = 0; j < menus.length; j++) {
                    var menuObj = menus[j];
                    var pid = menuObj['menu_id'];
                    if (pid == parent_id) {
                        var childObj = {}, menu_id = menuRoleObj['menu_id'], menu_url = menuRoleObj['menu_url'];
                        childObj['menu_id'] = menu_id;
                        childObj['parent_id'] = menuRoleObj['parent_id'];
                        childObj['menu_name'] = menuRoleObj['menu_name'];
                        childObj['menu_url'] = menu_url;
                        childObj['menu_icon'] = menuRoleObj['menu_icon'];
                        menuObj['menu_child'].push(childObj);
                    }
                }
            }
        }
    }
    return menus;
};

var __toParams = function (role) {
    return {
        role_id: role.role_id,
        is: role.role_id + "_",
        role_name: role.role_name,
        description: role.description,
    };
};


module.exports = router;

/* GET users listing. */
router.get('/', (req, res, next) => {
    res.render('admin/menu_role', {
        user: req.session.user,
        menus: req.session.menus,
        menu_active: req.session.menu_active['/menu_role'] || {},
        title: '菜单权限管理'
    });
});

router.get('/get_menu', async (req, res, next) => {
    var role_id = req.query.role_id;
    menuService.getAllMenu(async function (err, menus) {
        if (!!err){
            log.error("menu_role get menu: " + e.stack);
            return res.json({error:1, msg:"加载菜单失败，请联系管理员"});
        }

        var result = {error:0, data:{}};
        result.data.menus = formatMenus(menus);

        var ids = [];
        var role_menus = await roleService.getMenus(role_id);
        for (var i = 0; i < role_menus.length; i++) {
            ids.push(role_menus[i].menu_id+'');
        }
        result.data.menuId = ids;

        return res.json(result);
    });
});

router.get('/load', async (req, res, next) => {
    var {search, start, length, draw} = req.query;
    if (!start || !length || !draw) {
        return res.status(401).json("invoke error!");
    }

    var keywords = search?search.value.trim():null;
    var start  = parseInt(start) || 0;
    var length = parseInt(length) || 0;
    var draw   = parseInt(draw) || 0;

    roleService.getRoles(keywords, start, length, function (err, data) {
        if (!!err){
            return res.status(200).json({error:err.errCode, msg:err.message});
        }

        var result = { draw: draw, recordsTotal: data.count, recordsFiltered: data.count, data:[] };
        data.rows.forEach(function (role) {
            result.data.push(__toParams(role));
        });

        return res.status(200).json(result);
    });
});

router.post('/setMenu', async (req, res, next) => {
    const user = req.session.user;
    var role_id = req.body.e_id;
    var menus = req.body.e_menus || [];
    if (!role_id) {
        return res.json({error:1, msg:'无效角色'});
    }

    if (!_.isArray(menus)) {
        menus = [menus]
    }

    roleService.setMenus(role_id, menus, async function (err, result) {
        if (!!err){
            log.error("menu_role set menus: " + e.stack);
            return res.json({error:1, msg:"设置菜单失败，请联系管理员"});
        }

        await helper.setMenus(req, user.id);
        await helper.saveOpLog(user.id, user.user_name, user.name, "绑定菜单ID:" + role_id + ";roles:" + menus);

        return res.json({error:0, msg:"ok"});
    });
});
